package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vo.LoginVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements UserService {
    @Override
    public LoginVO login(LoginDto loginDto) {
        LoginVO loginVO = new LoginVO();

        if (StringUtils.isBlank(loginDto.getPhone()) || StringUtils.isBlank(loginDto.getPassword())){
            //游客登录 无需手机号和密码
            loginVO.setToken(AppJwtUtil.getToken(0L));
        }else {
            //正常登录 手机号和密码
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, loginDto.getPhone()));
            if (user == null){
                throw  new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //对前端密码进行加密
            String pwdFront = loginDto.getPassword();//前段密码,未加密
            String salt = user.getSalt();//盐
            //加密后的前端 密码 两个相加用md5算法进行加密
            String pwdFront2 = DigestUtils.md5DigestAsHex((pwdFront + salt).getBytes(StandardCharsets.UTF_8));
            if (!pwdFront2.equals(user.getPassword())){
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            LoginVO.UserDTO userDTO = new LoginVO.UserDTO();
            BeanUtils.copyProperties(user,userDTO);
            loginVO.setUser(userDTO);
            loginVO.setToken(AppJwtUtil.getToken(Long.valueOf(user.getId())));

        }

        return loginVO;
    }
}
